package com.train.mybatis.base;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.train.common.model.page.PageParam;
import com.train.common.model.page.PageSorted;
import com.train.common.resp.PageResp;
import com.train.mybatis.utils.MybatisUtils;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

public interface MyBaseMapper<T> extends BaseMapper<T> {

    Long DEFAULT_PAGE_PAGE_NO = 1L;

    Long DEFAULT_PAGE_SIZE = 20L;

    /**
     * 快速分页方法
     * @param pageParam
     * @param queryWrapper
     * @param pageSorted
     * @return
     */
    default PageResp<T> selectPage(PageParam pageParam, LambdaQueryWrapper<T> queryWrapper, PageSorted... pageSorted) {
        if (pageParam.getPageNo() == null) {
            pageParam.setPageSize(DEFAULT_PAGE_PAGE_NO);
        }
        if (pageParam.getPageSize() == null) {
            pageParam.setPageSize(DEFAULT_PAGE_SIZE);
        }
        //过滤非空元素
        List<PageSorted> pageSorteds = Arrays.stream(pageSorted).filter(Objects::nonNull).collect(Collectors.toList());
        //构建分页参数
        Page<T> buildPage = MybatisUtils.buildPage(pageParam, pageSorteds);
        //查询
        Page<T> page = selectPage(buildPage, queryWrapper);
        return new PageResp<>(page.getTotal(), page.getRecords());
    }
}
